package rpc.retry;

import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import rpc.client.RPCFuture;
import rpc.client.RpcClientHandler;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@EqualsAndHashCode(of = {"requestId"}, callSuper = true)
public class RetryTask extends Thread implements Delayed {

    private String requestId;
    RPCFuture future;
    RpcClientHandler clientHandler;
    long expire;
    public static int TIMEOUT = 3;
    public RetryTask(RPCFuture future, RpcClientHandler clientHandler) {
        this.future = future;
        this.requestId = future.getRequest().getRequestId();
        this.clientHandler = clientHandler;
        this.expire = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(TIMEOUT, TimeUnit.SECONDS);
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed o) {
        long delta = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
        return (int) delta;
    }

}
